import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class DemoJSON
{
	public static void DemoJsonArr(){
		String s = "{\"maps\": [0,1,2,{\"item\": \"xyz\"}]}";
		try {
			JSONObject test = new JSONObject(s);
			System.out.println("================before===============");
			System.out.println(test);
			System.out.println("================after===============");
			test.getInArray("maps", "item", "xyz").put("nam", "Nguyen");
			System.out.println(test);			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void DemoJson() {
		System.out.println("=======decode=======");
		String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";		

		JSONArray array;
		try {
			array = new JSONArray(s);
			System.out.println("======the 2nd element of array======");
			System.out.println(array.get(1));
			System.out.println();

			JSONObject obj2 = (JSONObject) array.get(1);
			System.out.println("======field \"1\"==========");
			System.out.println(obj2.get("1"));

			s = "{}";
			JSONObject obj = new JSONObject(s);
			System.out.println("======empty json object==========");
			System.out.println(obj);

			s = "[5,]";			
			array = new JSONArray(s);
			System.out.println("======array with only one element==========");
			System.out.println(array);

			s = "[5,,2]";
			array = new JSONArray(s);
			System.out.println("======array with empty element in the middle==========");
			System.out.println(array);
			 
			s = "[{\"1\":\"2\"},,2]";
			array = new JSONArray(s);
			System.out.println(array);
			obj = array.getJSONObject(0);
			obj.put("helo", new JSONObject("{\"1\":\"2\"}"));
			obj.getJSONObject("helo").put("ohman", "yesman");
			System.out.println("======ElementIsArray==========");
			System.out.println(obj);
			System.out.println(array);
					
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// test transaction
	public static void main(String[] args) {
		try {			
			//DemoJson();
			DemoJsonArr();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
